<?php

class Api_Xml extends Api
{
    protected $extensionFiles = 'xml';

    public function getOptions($url, $authorization)
    {
        $options = array(
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER     => array(
                'Accept: application/xml',
                'Content-Type: application/xml',
                'Authorization: Basic ' . $authorization
            ),
        );

        return $options;
    }

    public function encodeData($data, $type = 'issue')
    {
        if (empty($data)) {
            return null;
        }

        $node = null;
        if ($type !== false) {
            $node ='<'. $type. '/>';
        }

        $result = $this->arrayToXml($data, $node);
        return $result;
    }

    public function decodeData($data)
    {
        if (!trim($data)) {
            return array();
        }

        $xmlIterator = new SimpleXMLIterator($data);
        $result = $this->xmlToArray($xmlIterator);
        return $result;
    }

    public function arrayToXml($array, $rootElement = null, $xml = null) {
        $_xml = $xml;

        if ($_xml === null) {
            $node = ($rootElement) !== null ? $rootElement : '<issue/>';
            $_xml = new SimpleXMLElement($node);
        }
        foreach ($array as $k => $v) {
            if (is_array($v)) { //nested array
                $this->arrayToXml($v, $k);
            } else {
                $_xml->addChild($k, $v);
            }
        }

        return $_xml->asXML();
    }

    public function xmlToArray($xmlIterator)
    {
        //TODO нужно еще получение нескольких тасков.
        $result = array();
        foreach($xmlIterator as $property => $value) {
            if (!$value->count()) {
                $json = json_encode($value);
                $array = json_decode($json, true);
                $result[$xmlIterator->getName()][$property] = current($array);
            }
        }

        return $result;
    }

}